<?php

namespace app\Modules\Api\controllers;

use Yii;
use app\Modules\Api\models\Addr;
use app\filters\Json;
use app\helpers\Request;
use yii\data\Pagination;

/**
 * Class AddrController
 * @package app\Modules\Api\controllers
 */
class AddrController extends ControllerBase
{
    public function actionIndex()
    {
        $user_id = Request::strictpost('user_id','缺少用户id');
        $query = Addr::find()->where(['user_id'=>$user_id]);
        $count = $query->count();
        $pagination = new Pagination([
            'totalCount' => $count,
            'pageSize'=>Yii::$app->request->post('pageSize',6),
            'page'=>Yii::$app->request->post('page'),
        ]);
        $addrs = $query
            ->offset($pagination->offset)
            ->limit($pagination->limit)
            ->orderBy(['addrid'=>SORT_DESC])
            ->all();
        return Json::success([
            'addrs'=>$addrs,
            'addr_count'=>$count,
        ]);
    }

    /**
     * 创建
     * @return array
     */
    public function actionCreate()
    {
        $model = new Addr();

        if ($model->load(Yii::$app->request->post(),'') && $model->save()) {
            return Json::success();
        }
        return Json::error(strval(current($model->getFirstErrors())));
    }
    /**
     * 修改
     * @return array
     */
    public function actionUpdate()
    {
        $addrid = Request::strictpost('addrid','缺少地址id');
        $model = Addr::findOne($addrid);
        $post = Yii::$app->request->post();
        $post['user_id'] = $model->user_id;
        if ($model->load($post,'') && $model->save()) {
            return Json::success();
        }
        return Json::error(strval(current($model->getFirstErrors())));
    }

    /**
     * 删除
     * @return array
     */
    public function actionDelete()
    {
        $addrid = Request::strictpost('addrid','缺少地址id');
        $model = Addr::findOne($addrid);
        return $model&&$model->delete()?Json::success():Json::error();
    }

    /**
     * 设为默认
     * @return array
     */
    public function actionDefault()
    {
        $addrid = Request::strictpost('addrid','缺少地址id');
        $model = Addr::findOne($addrid);
        if(!$model)
            return Json::error('地址不存在');
        $model->setDefault();
        return Json::success();
    }
}